package me.stephenj.contactsweb.service;

import me.stephenj.contactsweb.mapper.ContactsMapper;
import me.stephenj.contactsweb.model.TestQueryVO;
import me.stephenj.contactsweb.model.TestVO;
import me.stephenj.contactsweb.model.TestVOJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ContactsService {
    @Autowired
    ContactsMapper contactsMapper;

    public List<TestVOJson> getContacts(TestQueryVO vo) {
        int page = vo.getPage();
        int pageSize = vo.getPageSize();
        int begin = (page - 1) * pageSize;
        int end = page * pageSize - 1;
        List<TestVO> testVOS = contactsMapper.getAll(vo);
        List<TestVOJson> testVOJsons = new ArrayList<>();
        if (testVOS.size() <= begin) {
            return testVOJsons;
        } else if (testVOS.size() <= end) {
            end = testVOS.size() - 1;
        }
        for (int i = begin; i <= end ; i++) {
            testVOJsons.add(testVOS.get(i).exportJson());
        }
        return testVOJsons;
    }

    public int getCount() {
        return contactsMapper.getCount();
    }

    public int insertContacts(TestVO vo) {
        return contactsMapper.insert(vo);
    }

    public int deleteContacts(String[] keys) {
        int number = 0;
        for (String key : keys) {
            number += 1;
            int ID = Integer.parseInt(key);
            contactsMapper.delete(ID);
        }
        return number;
    }

    public int updateContacts(TestVO vo) {
        return contactsMapper.update(vo);
    }
}
